<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 用户
 * @author www.dingwei.cn
 */
class User extends MY_Controller {
	
	public function __construct(){
		parent::__construct();
	}

    /**
     * 注册发送短信验证码
     */
    public function getRegisterVerifyCode(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
        );

        $this->formDataValidation($vConf);
        $code = mt_rand(10000,99999);
        $mobile = post('mobile');
        $tB = $this->mUser->mobileIsExist($mobile);
        if($tB){
            $this->appReturn(0, '手机号码已注册');
        }

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
		$msg = '您正在进行新用户注册登录操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }

    /**
     * 注册接口
     */
    public function register(){

        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('code', '验证码', 'required'),
            array('password', '密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);

        //获取参数
        $mobile = post('mobile');
        $code = post('code');
        $password = post('password');

        /**
         * 验证短信验证码
         */
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);//获取
        if(empty($tA)) $this->appReturn(0, '验证码错误');

        /**
         * 验证手机号是否存在
         */
        $result = $this->mUser->mobileIsExist($mobile);
        if ($result){
            $this->appReturn(0,'手机号码已注册');
        }

        /**
         * 注册帐号
         */
        $this->db->trans_begin();//开启事务

        $data = array(
            'mobile'	=> $mobile,
            'password'	=> setPassword($password),
            'nickname'		=> '商盟'.substr($mobile,-4),
            'gender'	=> 1,
            'business'	=> 1,//休息中
            'business_week'	=> ',1,2,3,4,5,6,7,',
            'honest'	=> 1, // 普通商户
            'balance'	=> 0,
            'percent'	=> 15,//平台佣金比例
            'first_order_reduce' => 0, //首单减免金额
            'min_consume' => 0,
            'able_use_coupon' => 2,//支持使用红包
            'able_cash_coupon' => 1,//不支持使用代金券
            'rank'	    => 1,//1初级 2中级 3高级
            'status'	=> 2,//-注册启动
            'shipping_type'	=> 2,//1商家配送 2平台配送
            'addtime'	=> time(),
            'jpush_code'=> uniqid().rand(1000, 9999).rand(100, 9999),
            'easemob_code'=> uniqid().rand(1000, 9999).rand(100, 9999)//环信账号
        );
        $data['easemob_pwd'] = setPassword($data['easemob_code']);//环信密码

        $tId = $this->mUser->save($data);
        if (!$tId){
            $this->db->trans_rollback();
            $this->appReturn(0,'注册失败');
        }

        //删除验证码
        if(!($this->mUser->deleteSmsCode($mobile))){
            $this->db->trans_rollback();
            $this->appReturn(0,'注册失败');
        }
        //注册环信账号
//        $result = easemob($data['easemob_code'], $data['easemob_pwd'] );
//
//        if($result['status'] == 0){
//            $this->db->trans_rollback();
//            $this->appReturn(0,'注册失败:'.$result['error']);
//        }

        $this->db->trans_commit();
        $this->appReturn(1,'注册成功');

    }

	/**
	 * 忘记密码发送短信验证码
	 */
	public function getForgetPasswordVerifyCode(){
	
		//表单验证
		$vConf = array(
				array('mobile', '手机号码', 'required|valid_mobile'),
		);
	
		$this->formDataValidation($vConf);
		$code = mt_rand(10000,99999);
		$mobile = $this->input->post('mobile');
		$tB = $this->mUser->mobileIsExist($mobile);
		if( ! $tB){
			$this->appReturn(0, '手机号码未注册');
		}
	
		$tA = $this->mUser->getSmsCodeLogInfo($mobile);
		if($tA){
			$time = time() - $tA['addtime'];
			if($time < 60){
				$this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
			}
		}
	
		$query = $this->mUser->addSmsCodeLog($mobile, $code);
		if( ! $query){
			$this->appReturn(0, '验证码发送失败');
		}
		$msg = '您正在进行支付密码设置操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        //获取用户信息
        $userInfo = $this->mUser->getInfo($this->userId, 0, true);
        if($userInfo['withdraw_password'] == 2){
            $msg = '您正在进行支付密码找回操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        }
		$query = sendSms($mobile, $msg);
		if( ! $query){
			$this->appReturn(0, '验证码发送失败');
		}
	
		$this->appReturn(1, '验证码已发送');
	}

    /**
     * 提现密码发送短信验证码
     */
    public function getWithdrawPasswordVerifyCode(){

        $code = mt_rand(10000,99999);
        $mobile = $this->userMobile;
        $tB = $this->mUser->mobileIsExist($mobile);
        if( ! $tB){
            $this->appReturn(0, '手机号码未注册');
        }

        $tA = $this->mUser->getSmsCodeLogInfo($mobile);
        if($tA){
            $time = time() - $tA['addtime'];
            if($time < 60){
                $this->appReturn(0, '请等'.(60 - $time).'s后重新发送');
            }
        }

        $query = $this->mUser->addSmsCodeLog($mobile, $code);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }
		$msg = '您正在进行支付密码设置操作，验证码为'.$code.'，10分钟内有效（戈壁客服绝不会索取此验证码，切勿转发或告知他人）。';
        $query = sendSms($mobile, $msg);
        if( ! $query){
            $this->appReturn(0, '验证码发送失败');
        }

        $this->appReturn(1, '验证码已发送');
    }

    /**
     *验证发送手机发送的验证码是否合法
     */
    public function verifyMobileCode(){
        //表单验证
        $vConf = array(
            array('mobile', '手机号码', 'required|valid_mobile'),
            array('type', '验证码类型', 'required|in_list[1,2]'),//1未注册 2已注册
            array('code', '验证码', 'required'),
        );
        $this->formDataValidation($vConf);
        $mobile = trim(post('mobile'));
        $code = trim(post('code'));
        $type = (int)post('type');

        //验证验证码
        $tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);
        if(empty($tA)) $this->appReturn(0, '验证码错误');
        /*$smsExpire = time() - getCustomConsumefig('sms_expire') * 3600;
        if($tA['addtime'] < $smsExpire){
            $this->appReturn(0, '验证码过期');
        }*/

        //验证手机
        if($type == 2){
            $userId = $this->mUser->mobileIsExist($mobile);
            if( ! $userId){
                $this->appReturn(0, '手机号码未注册');
            }
        }

        $this->appReturn(1, '验证成功');
    }

	/**
	 * 用户登录
	 */
	public function login(){

		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
				);
		$this->formDataValidation($vConf);
		$mobile = trim(post('mobile'));
		$password = setPassword(post('password'));
		$tA = $this->mUser->getInfoByMobileAndPassword($mobile, $password);
		if(empty($tA)){
			$this->appReturn(0, '用户不存在或密码错误');
		}
		if($tA['status'] < 2){
			$this->appReturn(0, '账户已禁用');	
		}
		
		//设置sessid
		$key = config_item('encryption_key');
		$sessionId = encryption($tA['id'].$key.time().mt_rand(10,100000));
		if(empty($sessionId)){
			$this->appReturn(0, '登录失败');				
		}

        $data = array(
            'merchant_id' => $tA['id'],
            'sessionid' => $sessionId,
            'type' => 1,
            'addtime' => time(),
        );

        $this->db->where(array('merchant_id' => $tA['id'], 'type' => 1));
        $tI = $this->mUser->count($this->mUser->tbSession);
        $number = getCustomConfig('merchant_number');
        if ($tI < $number){
            $tts = $this->mUser->insert($this->mUser->tbSession, $data);
        }else{
            $this->db->where(array('merchant_id' => $tA['id'], 'type' => 1))
                ->order_by('addtime asc');
            $tt = $this->mUser->getOne($this->mUser->tbSession);
            $this->db->where(array('merchant_id' => $tA['id'], 'sessionid' => $tt['sessionid'], 'type' => 1));
            $tts = $this->mUser->update($this->mUser->tbSession, $data);
        }
        if ($tts) {
            $data = array(
                'sessionid' => encode($sessionId),
                'mobile' => $mobile,
                'jpush_code' => $tA['jpush_code'],
                'easemob_name' => $tA['easemob_code'],
                'easemob_word' => $tA['easemob_pwd'],
            );

            $this->appReturn(1, '已登录', $data);
        }
//        if($this->mUser->addSession($tA['id'], $sessionId)){
//			$this->sessionId = $sessionId;
//			$data = array(
//                		'sessionid' => encode($sessionId),
//						'mobile' => $mobile,
//						'jpush_code' => $tA['jpush_code'],
//						'easemob_name' => $tA['easemob_code'],
//						'easemob_word' => $tA['easemob_pwd'],
//			);
//
//			$this->appReturn(1, '已登录', $data);
//		}
		
		$this->appReturn(0, '登录失败');
	}
	
	/**
	 * 忘记密码
	 */
	public function forgetPassword(){
		//表单验证
		$vConf = array(
					array('mobile', '手机号码', 'required|valid_mobile'),
					array('code', '验证码', 'required'),
					array('password', '密码', 'required|min_length[6]|max_length[15]'),
					array('re_password', '确认密码', 'required|matches[password]'),
				);
		$this->formDataValidation($vConf);	
		$mobile = trim($this->input->post('mobile'));
		$code = trim($this->input->post('code'));

		//验证验证码
		$tA = $this->mUser->getSmsCodeLogInfo($mobile, $code);	
		if(empty($tA)) $this->appReturn(0, '验证码错误');
		$smsExpire = time() - getCustomConfig('sms_expire') * 3600;
		if($tA['addtime'] < $smsExpire){
			$this->appReturn(0, '验证码过期');				
		}
		
		//验证手机
		$userId = $this->mUser->mobileIsExist($mobile);
		if( ! $userId){
			$this->appReturn(0, '手机号码未注册');
		}
		
		$data = array(
			       'password' => setPassword(post('password'))
				);
				
		if($this->mUser->save($data, $userId)){
			$this->mUser->deleteSmsCode($mobile);//删除验证码
			$this->appReturn(1, '密码已更改');
		}
		
		$this->appReturn(0, '修改失败');
	}


    /**
     * 修改密码
     */
    public function password(){
        //表单验证
        $vConf = array(
            array('old_password', '旧密码', 'required|min_length[6]|max_length[15]'),
            array('password', '新密码', 'required|min_length[6]|max_length[15]'),
            array('re_password', '确认密码', 'required|matches[password]'),
        );
        $this->formDataValidation($vConf);
        $mobile = $this->userMobile;
        $oldPassword = setPassword(post('old_password'));
        //验证手机
        $userId = $this->mUser->getInfoByMobileAndPassword($mobile, $oldPassword);
        if(empty($userId)){
            $this->appReturn(0, '原密码错误');
        }

        $data = array(
            'password' => setPassword(post('password'))
        );

        if($this->mUser->save($data, $this->userId)){
            $this->appReturn(1, '密码修改成功，请重新登录');
        }
        $this->appReturn(0, '修改失败');
    }
    
    /**
     * 上传头像
     */
    public function portrait(){
    	
    	$path = 'uploads/'.$this->port.'/'.$this->userId.'/portrait';
    	if(empty($_FILES['portrait'])){
    		$this->appReturn(0, '请选择上传头像');
    	}
    	
    	$tA = imageUpload($path, 'portrait', 'portrait', true, 250, 250);
    	if( ! $tA['status']){
    		$this->appReturn(0, '头像上传失败');
    	}
    	$rs = $this->mUser->save(array('portrait' => $tA['data']), $this->userId);
    	if($rs){
    		$this->appReturn(1, '头像上传成功', getImage($tA['data'], 'xs'));
    	}
    	$this->appReturn(0, '头像上传失败');
    }

    /**
     * 获取登录用户信息
     */
    public function getUserInfo(){
        $this->loadModel('AdmSettingModel', 'mSetting', 'admin');
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->loadModel('MerchantMessageModel', 'mMessage', 'merchant');
        $this->loadModel('MerchantCommentModel', 'mComment', 'merchant');

        //获取用户信息
        $info = $this->mUser->getInfo($this->userId, 0, true);
        $message = $this->mMessage->getMessageNumber($this->userId);
        $info['mobile'] = substr($info['mobile'],0,3).'****'.substr($info['mobile'],-4);
        $info['success_order_rate'] = $this->mOrder->getSuccessOrderRate($this->userId); // '4.0%';//成交率
        $info['operation_order_number'] = $this->mOrder->getOperateOrderNumber($this->userId); //待发货 待核销 总订单数量
        $info['operation_order_counts'] = $this->mOrder->getOperateOrderNumber($this->userId, 0, true); //待发货 待核销 总订单数量
        $score = $this->mComment->getStoreCommentScore($this->userId);
        if (isset($score['avg'])){
            $avg = sprintf("%.1f", $score['avg']);
        }else{
            $avg = '5.0';
        }

        $info['score'] = $avg;//店铺评分
        $info['service_order_number'] = $this->mOrder->getServiceOrderCount($this->userId);//售后中数量
        $info['message_number'] = $message['total'];//消息数量
        $info['order_message_number'] = $message['order']; //订单未读消息数量
        $info['system_message_number'] = $message['system']; //系统未读消息数量
        //获取到店 送货上门说明
        $desc = $this->mSetting->getExplain('to_store_desc,to_door_desc,reality_receive_explain,month_reality_recive_expain,merchant_discount_desc');
        $info['to_store_desc'] = $desc['to_store_desc']?str_replace('{base_url}', base_url(), $desc['to_store_desc']):'';
        $info['to_door_desc'] = $desc['to_door_desc']?str_replace('{base_url}', base_url(), $desc['to_door_desc']):'';
        $info['merchant_discount_desc'] = $desc['merchant_discount_desc']?str_replace('{base_url}', base_url(), $desc['merchant_discount_desc']):'';
        $info['month_reality_recive_expain'] = $desc['month_reality_recive_expain']?strip_tags(str_replace('{base_url}', base_url(), $desc['month_reality_recive_expain'])):'';
        $info['reality_receive_explain'] = $desc['reality_receive_explain']?strip_tags(str_replace('{base_url}', base_url(), $desc['reality_receive_explain'])):'';

        unset($info['supervise'],$info['business'],$info['honest'],$info['percent'],$info['county'],$info['shop_imgs']);
        //处理
//        $info['merchant_discount_desc']  = $this->view('order/info',['html'=>$info['merchant_discount_desc'],'title' =>'优惠说明'], '', '', '', true);

        $this->appReturn(1, '', $info);
    }

    /**
     * 获取app版本
     * type = 1 安卓
     * type = 2 ios
     */
    public function getAppVersionInfo(){

        $this->loadModel('AdmSettingModel', 'mSet', 'admin');

        //表单验证
        $vConf = array(
            array('type', 'app类型', 'required|in_list[1,2]'),
        );

        $type = get('type');
        $this->formDataValidation($vConf,array('type' => $type));
        if($type == 1){
            $tA = $this->mSet->get('app_android_update');
            $data = json_decode($tA, true);
        }else{
            $tA = $this->mSet->get('app_ios_update');
            $data = json_decode($tA, true);
        }

        $this->appReturn(1, '', $data[1]);
    }
}